#include "db.h"

DB* DB::instance = NULL;

/*
    Is singleton
    Provides a functionality for DataBase operations
*/
DB::DB() {
    // private constructor
}

DB* DB::getInstance() {
    if (instance == NULL) {
        instance = new DB();
    }
    return instance;
}

bool DB::connect(QString host, QString user, QString pass, QString dbname) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName("test");
    db.setUserName("root");
    db.setPassword("7981");
    db.setHostName("localhost");
    //db.driverName("mysql");


    /*bool ok = db.open();

    QSqlQuery query;
    query.exec("SELECT * FROM testTable");
    while(query.next()) {
        QString firstName = query.value(0).toString();
        QString secondName = query.value(1).toString();
        qDebug() << firstName << secondName;
    }*/
    return true;
}

bool DB::execute(QString query) {
    // @todo DB query
    return true;
}

QList<QString>* DB::select(QString query) {
    // @todo DB query
    return new QList<QString>();
}

QList<User*> DB::getUsers() {
    return users;
}

QList<Room*> DB::getRooms() {
    return this->rooms;
}

void DB::addUser(User* user) {
    users << user;
}

User* DB::findByLogin(QString login) {
    for (int i = 0; i < users.size(); i++) {
        if (users.at(i)->getLogin().compare(login) == 0) {
            return users.at(i);
        }
    }
    return NULL;
}

User* DB::findByIdentify(QString identify) {
    for (int i = 0; i < users.size(); i++) {
        if (users.at(i)->getIdentify().compare(identify) == 0) {
            return users.at(i);
        }
    }
    return NULL;
}

Room* DB::findRoom(QString roomName) {
    for (int i = 0; i < rooms.size(); i++) {
        if (rooms.at(i)->getName().compare(roomName) == 0) {
            return rooms.at(i);
        }
    }
    return NULL;
}

void DB::addRoom(Room *room) {
    this->rooms.append(room);
}
